<html>
    <head>
        <script src="../../resources/testharness.js"></script>
        <script src="../../resources/testharnessreport.js"></script>
        <script src="../../resources/testdriver.js"></script>
        <script src="../../resources/testdriver-vendor.js"></script>
    </head>
    <body>
        <button id="button1" onclick="testButton1()">Click Here</button>
        <button id="button2" onclick="testButton2()">Click Here Too</button>
        <button id="test" onclick="popup()" style="display:none"></button>
        <script>
            setup({explicit_done: true});

            var testNum = 0;
            var win;

            function popup() {
                win = window.open("about:blank", "blank");
                assert_not_equals(win, null);
            }

            function testButton1() {
                document.getElementById("test").click();
                ++testNum;
                closeWindowAndRunNextTest();
            }

            function testButton2() {
                var clickEvent = document.createEvent("MouseEvents");
                clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                document.getElementById("test").dispatchEvent(clickEvent);
                ++testNum;
                closeWindowAndRunNextTest();
            }

            function closeWindowAndRunNextTest() {
                if (!win)
                    nextTest();

                win.close();
                setTimeout(doneHandler, 1);

                function doneHandler() {
                    if (win.closed) {
                        setTimeout(nextTest, 1);
                        return;
                    }
                    setTimeout(doneHandler, 1);
                }
            }

            function nextTest() {
                if (testNum == 0) {
                  test(() => {
                    test_driver.click(button1);
                  }, 'Click button1');
                } else if (testNum == 1) {
                  test(() => {
                    test_driver.click(button2);
                  }, 'Click button2');
                } else {
                    done();
                }
            }

            if (window.testRunner) {
                nextTest();
            }
        </script>
    </body>
</html>
